from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Wechat
# Create your views here.


def index(request):
    context = {}
    params = request.GET.copy()
    status = params.get('status', None)
    if status is None:
        _obj_list = Wechat.objects.filter().order_by('-id')
    else:
        _obj_list = Wechat.objects.filter(status=status).order_by('-id')

    paginator = Paginator(_obj_list, 50)  # Show 20 contacts per page

    page = request.GET.get('page')
    try:
        _objs = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        _objs = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        _objs = paginator.page(paginator.num_pages)

    # r = get_redis()
    # 获取代理状态
    # proxies = Proxy.objects.filter(kind=Proxy.KIND_DOWNLOAD, status=Proxy.STATUS_SUCCESS)[:1]
    # if len(proxies) > 0:
    #     dt = datetime.now() - proxies[0].update_time
    #     _proxy_status = '正常' if dt.total_seconds() < 3600 else '异常'
    # else:
    #     _proxy_status = '异常'
    context.update({
        "active_nav": "wechats",
        "wechats": _objs,
        "params": params,
        # "downloader": r.llen(CRAWLER_CONFIG['downloader']) or 0,
        # "antispider": r.get(CRAWLER_CONFIG['antispider']) or 0,
        # "proxy_status": _proxy_status
    })

    return render(request, 'wechat/index.html', context)
